/******************************************************/
/***************** 数据库操作相关处理 *****************/
/******************************************************/

const { N, needParam } = require("../../core/utils");
const { getAnnoStr } = require("../../core/creator/mysql/_utils");
const { createTable, insertTable } = require("../../core/creator/mysql");

// 生成创建表格的sql语句
function getCreateTableSql(tableName = needParam(), addRows = []) {
  let sqlStr = "";
  const createSql = createTable(tableName);
  sqlStr = `${getAnnoStr(`创建${tableName}表${N}${createSql}`)}${N}`;
  if (addRows?.length) {
    const insertSql = insertTable(tableName, addRows);
    sqlStr += `${N}${getAnnoStr(`插入${tableName}表${N}${insertSql}`)}${N}`;
  }
  return sqlStr;
}

module.exports = {
  // 获取创建所有表的sql语句字符串
  getCreateTablesSqlStr(tablesMap = {}, isInsert = false) {
    let sqlStr = N;
    // 创建表、插入初始数据
    const names = Object.keys(tablesMap);
    names.forEach((name, ind) => {
      const { fields, insertRows = [] } = tablesMap[name];
      const str = getCreateTableSql(name, fields, isInsert ? insertRows : undefined);
      const isLast = ind === names.length - 1;
      sqlStr += `${str}${isLast ? "" : `${N}${N}${N}`}`;
    });
    return sqlStr;
  },
};
